package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.EsManagerMapper;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import pojo.SkuInfo;

import java.util.List;
import java.util.Map;

/*
elasticsearch搜索服务接口实现
 */
@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private EsManagerMapper esManagerMapper;

    //创建索引结构
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //一键导入索引库
    @Override
    public void importAll() {
        //远程调用skuFegin里的方法,不加入spuId条件进行查询，查询的是审核通过的所有sku
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");

        if (skuList==null || skuList.size()<0 ){
            throw  new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //skulist转换为json
        String jsonSkuString = JSON.toJSONString(skuList);
        //将json转换为skuinfo
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuString, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    //根据spuId同步数据到索引库中
    @Override
    public void importDataToESBySpuId(String spuId) {
        //远程调用skuFegin里的方法,加入spuId条件进行查询，查询的是审核通过的符合条件的sku
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if(skuList==null || skuList.size()<0){
            throw  new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //skulist转换为json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为skuinfo
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }
}
